package Messages;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.concurrent.Phaser;

import com.mysql.jdbc.ResultSet;

import Server.SQLConnection;
import ocsf.server.ConnectionToClient;
/**
 * This class implements the Add Reservation to db
 *   @author Shlomit Yosfan
 * @author Nofar Sutliman
 */
public class MessageAddReservation {

	private ConnectionToClient client ;
	private String[] str; 
	static int row1;
	/**
	 * Contractor of this class 
	 * @param str
	 * @param client
	 */
	
	public MessageAddReservation(String[] str, ConnectionToClient client) {
		this.client= client ;
		this.str= str; 
	}

	/**
	 * Adding  Reservation to the DB	
	 * @throws SQLException
	 * @throws IOException
	 */
	
	
	public void AddReservation() throws SQLException, IOException{
		
		SQLConnection sc = new SQLConnection();
		
		java.sql.PreparedStatement reservationId = sc.getConnection().prepareStatement("SELECT * FROM db.reservation;");
		java.sql.PreparedStatement clientId = sc.getConnection().prepareStatement("SELECT * FROM db.client where ClientID ='"+str[1]+"';");
		java.sql.PreparedStatement reservationInsert = sc.getConnection().prepareStatement("INSERT INTO db.reservation (ReservaionID,ClientID,ReservationPhone,RecipientFullName,RecipientAddress,DeliveryDate,Status,Description) VALUES(?,?,?,?,?,?,?,?);");
		
		ResultSet clientrs= (ResultSet) clientId.executeQuery();
		
		if (!clientrs.next())
		{
			ArrayList<Object> noClient=new ArrayList<Object>();
			noClient.add("NoClient");		
			noClient.add(str[1]);
			client.sendToClient(noClient);
		}
		else
		{
		
		
		ResultSet rs= (ResultSet) reservationId.executeQuery();
		row1 = 0;
		while(rs.next()){
			int temp = rs.getInt(1);
				if(row1>temp)
					row1=row1;
					else{
					row1=temp;}

		}
		
	
		reservationInsert.setInt(1, row1+1);					
		reservationInsert.setString(2,str[1]);
		reservationInsert.setString(3,str[3]);
		reservationInsert.setString(4,str[2]);
		reservationInsert.setString(5, str[4]);
		reservationInsert.setString(6, str[5]);
		reservationInsert.setString(7, str[6]);
		reservationInsert.setString(8, str[7]);

		reservationInsert.executeUpdate();
		reservationInsert.close();
	
		
							ArrayList<Object> reservation=new ArrayList<Object>();
							reservation.add("AddReservation");		
							client.sendToClient(reservation);
		
		}
		
		
	}
				
}
